package com.cuitrip.business.user;


import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.home.recommend.model.RecommendTravelTrip;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.tripservice.ServiceDetailActivity;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.business.user.proxy.UserInfoProxy;
import com.cuitrip.business.user.ui.TripHolderView;
import com.cuitrip.component.item.ItemLayout;
import com.cuitrip.component.statelayout.StateLayout;
import com.cuitrip.resource.DrawableClass;
import com.cuitrip.resource.ResourceManager;
import com.cuitrip.service.R;
import com.cuitrip.util.PlatformUtil;
import com.cuitrip.util.text.TextProxy;
import com.cuitrip.util.time.InputTime;
import com.cuitrip.util.time.OutputTime;
import com.cuitrip.util.time.TimeUtil;
import com.lab.adapter.HolderViewAdapter;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragment;
import com.lab.component.list.LinearListView;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.proxy.ApiProxy;
import com.lab.network.proxy.ApiProxyBuilder;
import com.lab.network.proxy.ApiProxyCallBack;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.ArrayUtil;
import com.lab.utils.ImageHelper;
import com.lab.utils.MessageUtils;
import com.lab.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;


/**
 * Created ak on 7/16.
 * “关于我”的界面
 */
public class PersonalFragment extends CustomUiFragment /*implements IProxyCallback*/ {

    private static final int REQUEST_CODE_EDIT_SELF_INFO = 21;
    /**
     * This class contains all butterknife-injected Views & Layouts from layout file 'ct_my_profile.xml'
     * for easy to all layout elements.
     *
     * @author ButterKnifeZelezny, plugin for Android Studio by Avast Developers (http://github.com/avast)
     */

    @Bind(R.id.selfUserIcon)
    ImageView selfUserIcon;
    @Bind(R.id.selfUserName)
    TextView selfUserName;
    @Bind(R.id.selfUserInfo)
    TextView selfUserInfo;
    @Bind(R.id.selfUserIntroduce)
    TextView selfUserIntroduce;
    @Bind(R.id.vertifiedView)
    ImageView vertifiedView;
    @Bind(R.id.register_layout)
    ItemLayout mRegisterLayout;
    @Bind(R.id.cert_layout)
    ItemLayout mCertLayout;
    @Bind(R.id.hobby_layout)
    ItemLayout mHobbyLayout;
    @Bind(R.id.language_layout)
    ItemLayout mLanguageLayout;
    @Bind(R.id.layout)
    View layout;
    @Bind(R.id.service_layout)
    View serviceLayout;
    @Bind(R.id.trip_list)
    LinearListView tripListView;
    @Bind(R.id.whose_service)
    TextView whoseServiceView;
    @Bind(R.id.state_layout)
    StateLayout mStateLayout;
    ApiProxy apiProxy;
    private String uid;
    private String title;
    private HolderViewAdapter mAdapter;
    private List<RecommendTravelTrip> mTripList = new ArrayList<RecommendTravelTrip>();
    private boolean showService = true;
    public IProxyCallback callBack = new ApiProxyCallBack<CtUserInfo>() {
        @Override
        public void doPreWork(CtApiResponse response) {
            hideLoading();
        }

        @Override
        public boolean onSuccess(CtUserInfo data, CtApiResponse response) {
            if (!isAdded()){
                return false;
            }
            if (LoginInstance.getInstance().isLogin()) {
                if (uid.equals(LoginInstance.getInstance().getUserInfo().getUid())) {
                    LoginInstance.updateProfile(AppCoreRuntime.context, data, false);
                }
            }
            bindView(data);
            mStateLayout.changeState(StateLayout.State.INIT);
            return super.onSuccess(data, response);
        }

        @Override
        public boolean onFaild(CtApiResponse response) {
            if (!isAdded()){
                return false;
            }
            String msg;
            if (response != null && !TextUtils.isEmpty(response.msg)) {
                msg = response.msg;
            } else {
                msg = PlatformUtil.getInstance().getString(R.string.feedback_data_err);
            }
            MessageUtils.showToast(msg);
            mStateLayout.changeState(StateLayout.State.NoNetwork);
            return false;
        }
    };

    public void setUid(String uid) {
        this.uid = uid;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if(isAdded()){
            apiProxy = ApiProxyBuilder.getBuilder().addApiCallBack(ApiManager.GET_USER_INFO, callBack).build();
        }
        return super.onCreateView(inflater, container, savedInstanceState, R.layout.ct_my_profile);
    }

    @Override
    public void initView() {
        ButterKnife.bind(this, getView());
        if (!TextUtils.isEmpty(uid)) {
            refreshUserInfo();
        }
        mAdapter = new HolderViewAdapter(getActivity(), mTripList, TripHolderView.class);
        tripListView.setAdapter(mAdapter);
    }

    public void initListener() {
        mStateLayout.setOnClickStateLayoutListener(new StateLayout.OnClickStateLayoutListener() {
            @Override
            public void onClick(StateLayout.State state) {
                refreshUserInfo();
            }
        });
        tripListView.setOnItemClickListener(new LinearListView.OnItemClickListener() {
            @Override
            public void onItemClick(LinearListView parent, View view, int position, long id) {
                RecommendTravelTrip recommendTravelTrip = (RecommendTravelTrip) parent.getAdapter().getItem(position);
                ServiceDetailActivity.start(getHostActivity(), recommendTravelTrip.getSid());
            }
        });
    }

    public void refreshUserInfo() {

        if(isAdded()){
            mStateLayout.changeState(StateLayout.State.Loading);
            UserBusiness.getUserInfo(apiProxy, uid);

        }
    }

    private void bindView(CtUserInfo userInfo) {
        selfUserName.setText(userInfo.getNick());
        StringBuilder sb=new StringBuilder();
        if (!TextUtils.isEmpty(userInfo.getCity())){
            sb.append(userInfo.getCity());
            if (!TextUtils.isEmpty(userInfo.getCareer())){
                sb.append("/");
            }
        }
        if (userInfo.isIdentityValidated()){
            vertifiedView.setImageDrawable(ResourceManager.getDrawable(DrawableClass.VeritifiedDrawable));
            vertifiedView.setVisibility(View.VISIBLE);
        }else{
            vertifiedView.setVisibility(View.GONE);
        }
        if(!TextUtils.isEmpty(userInfo.getCareer())){
            sb.append(userInfo.getCareer());
        }
        selfUserInfo.setText(sb.toString());
        if (TextUtils.isEmpty(selfUserInfo.getText().toString())) {
            selfUserInfo.setVisibility(View.GONE);
        }

        ImageHelper.displayCtImage(userInfo.getHeadPic(), selfUserIcon, null);
        mRegisterLayout.setmRightText(
                TimeUtil.formatTime(
                        InputTime.build(userInfo.getGmtCreated()),
                        OutputTime.getLocalInstance(OutputTime.OutputType.Type_DAY)
                )
        );
        if (TextUtils.isEmpty(userInfo.getIntroduce())) {
            selfUserIntroduce.setVisibility(View.GONE);
        } else {
            selfUserIntroduce.setText(userInfo.getIntroduce());
        }
        mHobbyLayout.setmRightText(Utils.getText(userInfo.getInterests(), getString(R.string.value_no_set)));
        mLanguageLayout.setmRightText(Utils.getText(userInfo.getLanguage(), getString(R.string.value_no_set)));
        if (userInfo.isEmailValidated() || userInfo.isIdentityValidated() || userInfo.isPhoneValidated() ||userInfo.isWechatValidated()||userInfo.isFacebookValidated()||userInfo.isGoogleValidated()) {
            mCertLayout.setRightTextSize(21.f);
            mCertLayout.setmRightText(UserInfoProxy.getInstance().getFullBindBuilder(userInfo));
            mCertLayout.getmRightTextView().setTag("font:icon");
        } else {
            mCertLayout.setRightTextSize(17.f);
            mCertLayout.getmRightTextView().setTag(null);
            mCertLayout.setmRightText(getString(R.string.value_no_set));
        }
        mCertLayout.setmRightText(UserInfoProxy.getInstance().getFullBindBuilder(userInfo));
        if (!isSelf() && showService) {
            serviceLayout.setVisibility(View.VISIBLE);
            inflateTripList(userInfo, userInfo.getTravelTripList());
        } else {
            serviceLayout.setVisibility(View.GONE);
        }
    }

    private boolean isSelf() {
        if (!LoginInstance.getInstance().isLogin()) {
            return false;
        }
        return uid.equals(LoginInstance.getInstance().getUserInfo().getUid());
    }

    private void inflateTripList(CtUserInfo userInfo, List<RecommendTravelTrip> tripList) {
        if (ArrayUtil.isNullOrEmpty(tripList)) {
            serviceLayout.setVisibility(View.GONE);
            return;
        } else {
            mTripList.clear();
            mTripList.addAll(tripList);
            mAdapter.notifyDataSetChanged();
        }
        String text = TextProxy.getInstance().formatWithSingleAndMore(tripList.size(), R.string.user_attribute_trip_one, R.string.user_attribute_trip_more);
        whoseServiceView.setText(text);
    }

    @Override
    public boolean initCloseTopBar() {
        return true;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        return null;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_EDIT_SELF_INFO) {
            refreshUserInfo();
        }
    }

    public void setShowService(boolean showService) {
        this.showService = showService;
    }
}

